package com.codeoss.framework.util;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.codeoss.framework.context.UserContext;
import com.codeoss.framework.data.metadata.Table;
import com.codeoss.module.ir.model.IrModel;
import com.codeoss.module.ir.model.IrModelAccess;
import com.codeoss.module.ir.service.IIrModelAccessService;
import com.codeoss.module.ir.service.IIrModelService;

@Component
public class PermissionUtil {
	@Autowired
	private IIrModelService irModelService;
	@Autowired
	private IIrModelAccessService irModelAccessService;
	
	public boolean hasRole(String role) {
		UserContext userContext=UserContext.getCurrentUserContext();
		List<String> roleCodeList=userContext.getRoleCodeList();
		if(roleCodeList!=null && roleCodeList.contains(role)) {
			return true;
		}
		return false;
	}
	
	public void hasPermission(Table table,String op) {
		IrModel irModel=irModelService.getIrModelByTableName(table.getTableName());
		QueryWrapper<IrModelAccess> accessQuery=new QueryWrapper<IrModelAccess>();
		accessQuery.eq("ir_model_id",irModel.getId());
		List<IrModelAccess> accessList=irModelAccessService.list(accessQuery);
		if(accessList.size()==0) {
			return ;
		}
		UserContext userContext=UserContext.getCurrentUserContext();
		for(int i=0;i<accessList.size();i++) {
			IrModelAccess irModelAccess=accessList.get(i);
			if(userContext.getRoleIdList().contains(irModelAccess.getResRoleId())) {
				if("select".equals(op)) {
					if(irModelAccess.getPermSelect()!=null && irModelAccess.getPermSelect().booleanValue()) {
						return ;
					}
				}else if("insert".equals(op)) {
					if(irModelAccess.getPermInsert()!=null && irModelAccess.getPermInsert().booleanValue()) {
						return ;
					}
				}else if("update".equals(op)) {
					if(irModelAccess.getPermUpdate()!=null && irModelAccess.getPermUpdate().booleanValue()) {
						return ;
					}
				}else if("delete".equals(op)) {
					if(irModelAccess.getPermDelete()!=null && irModelAccess.getPermDelete().booleanValue()) {
						return ;
					}
				}
			}
		}
		throw new RuntimeException("没有权限");
	}
}
